/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * HomeForm.java
 *
 * Created on 20-gen-2011, 20.01.41
 */

package mediawheregui;

import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.text.*;

import java.awt.*;
import java.awt.event.*;

import java.net.URL;
import java.io.IOException;
import java.io.File;
import java.util.StringTokenizer;
import java.util.ArrayList;

import java.util.Iterator;
import java.util.Collection;
import java.util.List;

import org.slf4j.impl.*;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.embedded.EmbeddedSolrServer;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.request.AbstractUpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrDocument;
import org.apache.commons.codec.*;
import org.apache.commons.httpclient.*;
import org.apache.commons.io.*;
import org.apache.commons.logging.*;


/**
 *
 * @author gioak
 */
public class HomeForm extends javax.swing.JFrame {

    /** Creates new form HomeForm */
    public HomeForm() {
        initComponents();
        
        String homePath = System.getenv("HOME");
        String logoPath = homePath + "/.mediawhere/images/logo.jpeg";
        Image logo = new ImageIcon(logoPath, "logo").getImage();
        this.setIconImage(logo);

        //init SearchButton
        Icon lensIcon = createImageIcon("images/lens.gif", "a lens icon");
        searchButton.setIcon(lensIcon);

        //init homeArea
        String[] initString = {
                "" + "\n", "   Quick Tips\n\n",                            //icon, bold
                "       ->  You must use upper and lower case, Search is case-sensitive\n\n", //regular
        };

        String[] initStyles = {"icon", "bold", "regular"};

        StyledDocument doc = jTextPane1.getStyledDocument();

        Style def = StyleContext.getDefaultStyleContext().
                        getStyle(StyleContext.DEFAULT_STYLE);

        Style regular = doc.addStyle("regular", def);
        StyleConstants.setFontFamily(def, "SansSerif");

        Style s = doc.addStyle("bold", regular);
        StyleConstants.setBold(s, true);

        s = doc.addStyle("icon", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_CENTER);

        /*ImageIcon lampIcon = createImageIcon("images/icona.freccia.gif","an arrow icon");
        if (lampIcon != null) {
            StyleConstants.setIcon(s, lampIcon);
            

        }*/

       /* s = doc.addStyle("icon", regular);
        StyleConstants.setAlignment(s, StyleConstants.ALIGN_RIGHT);


        ImageIcon arrowIcon = createImageIcon("images/icona.freccia.gif",
                                            "an arrow icon");
        if (arrowIcon != null) {
            StyleConstants.setIcon(s, arrowIcon);
        }*/

        //Style s1 = doc.addStyle("icon", regular);
        //StyleConstants.setAlignment(s1, StyleConstants.ALIGN_CENTER);

        ImageIcon lampIcon = createImageIcon("images/lampadina.gif","a lamp icon");
        if (lampIcon != null) {
            StyleConstants.setIcon(s, lampIcon);
        }
       


        try {
            for (int i=0; i < initString.length; i++) {
                doc.insertString(doc.getLength(), initString[i],
                                 doc.getStyle(initStyles[i]));
            }
        } catch (BadLocationException ble) {
            System.err.println("Couldn't insert initial text into text pane.");
        }
        
    }


    protected static ImageIcon createImageIcon(String path, String description) {
        //java.net.URL imgURL = HomeForm.class.getResource(path);
        String homePath = System.getenv("HOME");
        String imagePath= homePath + "/.mediawhere/" + path;
        if (imagePath != null) {
            return new ImageIcon(imagePath, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /*protected static ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = "/home/gioak/NetBeansProjects/lamapdina.gif"; //TextSamplerDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }*/

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        searchPanel = new javax.swing.JPanel();
        searchLabel = new javax.swing.JLabel();
        searchTextField = new javax.swing.JTextField();
        searchButton = new javax.swing.JButton();
        textAreaPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextPane1 = new javax.swing.JTextPane();
        jPanel1 = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        searchMenu = new javax.swing.JMenu();
        helpMenu = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("MediaWhere");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        searchLabel.setText("Search:");

        searchTextField.setToolTipText("Quick Search in Mediawhere");

        searchButton.setText("Find Now");
        searchButton.setToolTipText("Search your file");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout searchPanelLayout = new javax.swing.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(searchPanelLayout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addComponent(searchLabel)
                .addGap(3, 3, 3)
                .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(searchButton)
                .addContainerGap(21, Short.MAX_VALUE))
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, searchPanelLayout.createSequentialGroup()
                .addContainerGap(27, Short.MAX_VALUE)
                .addGroup(searchPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(searchLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton))
                .addContainerGap())
        );

        jScrollPane1.setViewportView(jTextPane1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 517, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 35, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout textAreaPanelLayout = new javax.swing.GroupLayout(textAreaPanel);
        textAreaPanel.setLayout(textAreaPanelLayout);
        textAreaPanelLayout.setHorizontalGroup(
            textAreaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textAreaPanelLayout.createSequentialGroup()
                .addGroup(textAreaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE))
                .addContainerGap())
        );
        textAreaPanelLayout.setVerticalGroup(
            textAreaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(textAreaPanelLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        searchMenu.setText("Search");
        searchMenu.setToolTipText("Search Menù");
        jMenuBar1.add(searchMenu);

        helpMenu.setText("Help");
        helpMenu.setToolTipText("How to use Mediawhere");
        jMenuBar1.add(helpMenu);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(textAreaPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(51, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(searchPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(textAreaPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(93, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed

        /* String text = searchTextField.getText();
        jTextPane1.setText(text);*/
        try {
            ArrayList<String> result = new ArrayList();
            SolrDocumentList docTot = new SolrDocumentList();//lista contenente tutti gli oggetti solrDocument ottenuti dalle query(mi serve nella ResultForm)
            String finalResult = new String();
            boolean noResult = true;
            String find = searchTextField.getText();
            //String queryString = this.createSolrQuery(find);

            //SolrServer solr = getSolrServer();

            String urlString = "http://localhost:8983/solr";

            SolrServer solr = new CommonsHttpSolrServer(urlString);



            SolrQuery query = new SolrQuery();
            SolrQuery query1 = new SolrQuery();
            query.set("q", find);
            query.set("fl", "*");
            query.set("rows", "100000");
            query1.set("q", "*:*");
            query1.set("rows", "100000");
            //query1.set("fl", "*");
            //query.set("q.op", "OR");
            //query.set("q", "*:*");
            //query.set("fq", "*:"+ find);
            //query.setQuery(queryString);
            //String[] array = {"author:"+ find, "attr_filename:"+ find};
            //query.set("q", "*:*");
            //query.set("q.op", "OR");
            //query.add("fq", "attr_filename:" + find);
            //query.add("fq", "author:"+find);
            //query.set("fq", "author:"+ find + " OR attr_filename:"+ find +" OR id:"+ find);
            System.out.println(query.toString());



            //query.set("q.op", "OR");
            //query.set("fq", "author:" + find);

            QueryResponse rsp = solr.query(query);
            SolrDocumentList docs = rsp.getResults();

            QueryResponse rsp1 = solr.query(query1);
            SolrDocumentList docs1 = rsp1.getResults();



            /* if (docs.size() == 0 && docs1.size() == 0) {
            jTextPane1.setText("NO RESULT FOR:" + find);
            } */
            if (docs.size() != 0)//risultato della prima query(indicizzazione)
            {
                noResult = false;
                SolrDocument doc = new SolrDocument();
                for (int i = 0; i < docs.size(); i++) {
                    doc = docs.get(i);
                    //Collection<String> list = doc.getFieldNames();
                    String prova = (String) doc.get("id");
                    String path = "";
                    StringTokenizer strTok = new StringTokenizer(prova, "|");
                    while (strTok.hasMoreTokens()) {
                        path = strTok.nextToken();
                    }
                    result.add(path);
                    docTot.add(doc);



                    /*Iterator<String> it = list.iterator();
                    String aut = new String();

                    while (it.hasNext()) {
                    aut = it.next();
                    if(aut.equals("id"))
                    {
                    String tmp = (String) doc.get(aut);
                    String path ="";
                    StringTokenizer strTok = new StringTokenizer(tmp,"|");
                    while(strTok.hasMoreTokens())
                    path = strTok.nextToken();
                    jTextPane1.setText(path + "\n");
                    //System.out.println(aut);
                    //System.out.println(doc.get(aut));
                    }
                    }*/
                }
            }
            if (docs1.size() != 0)//risultato della seconda query
            {
                SolrDocument doc = new SolrDocument();
                for (int i = 0; i < docs1.size(); i++) {
                    doc = docs1.get(i);
                    Collection<String> list = doc.getFieldNames();
                    Iterator<String> it = list.iterator();
                    String temp = new String();

                    while (it.hasNext()) {
                        temp = it.next();
                        if (doc.get(temp).getClass() != temp.getClass())//controllo se il valore del campo è una Stringa
                        {
                            continue;
                        }
                        String value = (String) doc.get(temp);
                        if (value.equals(find)) {
                            noResult = false;
                            String prova = (String) doc.get("id");
                            String path = "";
                            StringTokenizer strTok = new StringTokenizer(prova, "|");
                            while (strTok.hasMoreTokens()) {
                                path = strTok.nextToken();
                            }
                            result.add(path);
                            docTot.add(doc);
                            break;

                        }

                    }
                }

            }

            if (noResult == true) {
                //jTextPane1.setText("NO RESULTS FOUND!!!\n");
            } else {
                for (int i = 0; i < result.size(); i++) {
                    finalResult = finalResult + result.get(i) + "\n";
                }
                System.out.println(finalResult);
               // jTextPane1.setText(finalResult);
            }

            ResultForm rf = new ResultForm(result, docTot, find);

        } catch (SolrServerException ex) {
            Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MalformedURLException ex) {
            Logger.getLogger(HomeForm.class.getName()).log(Level.SEVERE, null, ex);
        }

       /* Dialog fileResult = new Dialog(this);
        fileResult.setTitle("Files found");
        File file = new File("/home/gioak/pippo.txt");
        fileResult.setVisible(true);*/


    }//GEN-LAST:event_searchButtonActionPerformed

   /* public SolrServer getSolrServer(){
    //the instance can be reused
    return new EmbeddedSolrServer(new CoreContainer(),"http://localhost:8983/solr");
}*/

    /*public String createSolrQuery(String find)
    {
        //String first = "select/?indent=on&q=";
        //String second = "&fl=*";
        String query = "?indent=on&q=video&fl=name,id";
        return query;
    }*/

    /**
    * @param args the command line arguments
    */

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                    new HomeForm().setVisible(true);
               
            }
        });
    }



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu helpMenu;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextPane jTextPane1;
    private javax.swing.JButton searchButton;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JMenu searchMenu;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JTextField searchTextField;
    private javax.swing.JPanel textAreaPanel;
    // End of variables declaration//GEN-END:variables


 


  }


